import type { EffectType, PlatformTypeValue } from '../../types/interfaces'
import { BeautifyLink } from '../page_enhancer/appearance/beautify_link'
import { CommitIcons } from '../page_enhancer/appearance/commit_icons'
import { DirTimeSimplifier } from '../page_enhancer/appearance/dir_time_simplifier'
import { ElementHider } from '../page_enhancer/appearance/element_hider'
import { FileIcons } from '../page_enhancer/appearance/file_icons'
import { HideSearchHistory } from '../page_enhancer/appearance/hide_search_history'
import { HideSearchHotLists } from '../page_enhancer/appearance/hide_search_hot_lists'
import { HideSearchSuggestions } from '../page_enhancer/appearance/hide_search_suggestions'
import { GreasyForkScriptInstalls } from '../page_enhancer/appearance/platform/greasy_fork/script_installs'
import { StyleEnhancement } from '../page_enhancer/appearance/style_enhancement'
import { ThemeInherit } from '../page_enhancer/appearance/theme_inherit'
import { ThemeStyle } from '../page_enhancer/appearance/theme_style'
import { ThemeSync } from '../page_enhancer/appearance/theme_sync'
import { CopyCopyright } from '../page_enhancer/content/copy_copyright'
import { CopyProtection } from '../page_enhancer/content/copy_protection'
import { PayWallHandler } from '../page_enhancer/content/paywall_handler'
import { DiscussionAnalytics } from '../page_enhancer/data_presentation/discussion_analytics'
import { FloorMarker } from '../page_enhancer/data_presentation/floor_marker'
import { GreasyForkFeedbackGroup } from '../page_enhancer/data_presentation/platform/greasy_fork/feedback_group'
import { GreasyForkScriptValuation } from '../page_enhancer/data_presentation/platform/greasy_fork/script_valuation'
import { GreasyForkStatsPanel } from '../page_enhancer/data_presentation/platform/greasy_fork/stats_panel'
import { GreasyForkTimeHelper } from '../page_enhancer/data_presentation/platform/greasy_fork/time_helper'
import { UserAnalytics } from '../page_enhancer/data_presentation/platform/greasy_fork/user_analytics'
import { TimeInterval } from '../page_enhancer/data_presentation/time_interval'
import { AutoPagination } from '../page_enhancer/interaction/auto_pagination'
import { BlockLogin } from '../page_enhancer/interaction/block_login'
import { CleanSearchHistory } from '../page_enhancer/interaction/clean_search_history'
import { ConversationFlow } from '../page_enhancer/interaction/conversation_flow'
import { ImageDetail } from '../page_enhancer/interaction/image_detail'
import { ImagePreview } from '../page_enhancer/interaction/image_preview'
import { KeyboardPagination } from '../page_enhancer/interaction/keyboard_pagination'
import { LinkDirect } from '../page_enhancer/interaction/link_direct'
import { MarkRead } from '../page_enhancer/interaction/mark_read'
import { NewTabLinks } from '../page_enhancer/interaction/new_tab_links'
import { GreasyForkFeedbackMark } from '../page_enhancer/interaction/platform/greasy_fork/feedback_mark'
import { GreasyForkScriptMark } from '../page_enhancer/interaction/platform/greasy_fork/script_mark'
import { QuickDownload } from '../page_enhancer/interaction/quick_download'
import { QuickScroll } from '../page_enhancer/interaction/quick_scroll'
import { StealthSearch } from '../page_enhancer/interaction/stealth_search'
import { SuperSearch } from '../page_enhancer/interaction/super_search'
import { SvgCopy } from '../page_enhancer/interaction/svg_copy'
import { AnswerNavigator } from '../page_enhancer/navigation/answer_navigator'
import { NavbarMenu } from '../page_enhancer/navigation/navbar_menu'
import { GreasyForkScriptNavigator } from '../page_enhancer/navigation/platform/greasy_fork/script_navigator'
import { GreasyForkSearchNavigator } from '../page_enhancer/navigation/platform/greasy_fork/search_navigator'

export type FeatureStatus = 'supported' | 'not-supported' | 'not-needed' | 'experimental'
export type FeatureHandler = (enabled: boolean, first: boolean) => void | Promise<void>

export interface FeatureMeta {
  name: string
  description: string | (() => string)
  category: FeatureCategory
  icon: string
  status: FeatureStatus
  show?: boolean
  defaultEnabled?: boolean
  effectType?: EffectType.IMMEDIATE | EffectType.MIXED
  dependencies?: ModuleId[]
  version?: string
  releaseDate?: string
  changelog?: string
  usePageTypeIsolation?: boolean
  loginRequired?: boolean
  isLoggedIn?: boolean
}

export interface FeatureConfig extends Partial<FeatureMeta> {
  pageTypeValidator?: () => boolean // 页面类型验证函数
}

export type ModulePlatformConfig = {
  [featureId in ModuleId]: {
    meta: FeatureMeta
    supportedPlatforms?: Partial<Record<PlatformTypeValue, FeatureConfig>>
  }
}

export interface FeatureItem extends FeatureMeta {
  enabled: boolean
  id: ModuleId
  isCustomDescription: boolean
}

export interface SetFeatureEnabledOptions {
  /** 生效类型（立即/延迟等） */
  effectType?: EffectType
  /** 是否首次设置（用于初始化） */
  first?: boolean
  /** 是否临时变更（不保存到缓存） */
  temporary?: boolean
}

// 支持的模块枚举，没有包含特殊的AdEngine、TocEngine
// 【特别注意】这里的顺序会影响模块的加载顺序！！！
export const AppModule = {
  // 基础模块（优先加载）
  StyleEnhancement: { id: 'style-enhancement', className: 'StyleEnhancement' },
  ElementHider: { id: 'element-hider', className: 'ElementHider' },

  AdEngine: { id: 'ad-engine', className: 'AdEngine' }, // AdEngine 必须在 ElementHider 之后
  TocEngine: { id: 'toc-engine', className: 'TocEngine' },

  NavbarMenu: { id: 'navbar-menu', className: 'NavbarMenu' },
  QuickScroll: { id: 'quick-scroll', className: 'QuickScroll' },
  AnswerNavigator: { id: 'answer-navigator', className: 'AnswerNavigator' },
  CopyCopyright: { id: 'copy-copyright', className: 'CopyCopyright' },
  CopyProtection: { id: 'copy-protection', className: 'CopyProtection' },
  LinkDirect: { id: 'link-direct', className: 'LinkDirect' },
  FloorMarker: { id: 'floor-marker', className: 'FloorMarker' },
  BlockLogin: { id: 'block-login', className: 'BlockLogin' },
  PayWallHandler: { id: 'pay-wall-handler', className: 'PayWallHandler' },
  StealthSearch: { id: 'stealth-search', className: 'StealthSearch' },
  NewTabLinks: { id: 'new-tab-links', className: 'NewTabLinks' },
  ThemeInherit: { id: 'theme-inherit', className: 'ThemeInherit' },
  ThemeSync: { id: 'theme-sync', className: 'ThemeSync' },
  ThemeStyle: { id: 'theme-style', className: 'ThemeStyle' },
  BeautifyLink: { id: 'beautify-link', className: 'BeautifyLink' },
  TimeInterval: { id: 'time-interval', className: 'TimeInterval' },
  AutoPagination: { id: 'auto-pagination', className: 'AutoPagination' },
  MarkRead: { id: 'mark-read', className: 'MarkRead' },
  SuperSearch: { id: 'super-search', className: 'SuperSearch' },
  SvgCopy: { id: 'svg-copy', className: 'SvgCopy' },
  KeyboardPagination: { id: 'keyboard-pagination', className: 'KeyboardPagination' },
  HideSearchHistory: { id: 'hide-search-history', className: 'HideSearchHistory' },
  HideSearchSuggestions: { id: 'hide-search-suggestions', className: 'HideSearchSuggestions' },
  // 【注意】这里隐藏历史在清理历史之前
  HideSearchHotLists: { id: 'hide-search-hot-lists', className: 'HideSearchHotLists' },
  CleanSearchHistory: { id: 'clean-search-history', className: 'CleanSearchHistory' },
  ConversationFlow: { id: 'conversation-flow', className: 'ConversationFlow' },
  DiscussionAnalytics: { id: 'discussion-analytics', className: 'DiscussionAnalytics' },
  QuickDownload: { id: 'quick-download', className: 'QuickDownload' },
  ImageDetail: { id: 'image-detail', className: 'ImageDetail' },
  ImagePreview: { id: 'image-preview', className: 'ImagePreview' },
  UserAnalytics: { id: 'user-analytics', className: 'UserAnalytics' },
  FileIcons: { id: 'file-icons', className: 'FileIcons' },
  CommitIcons: { id: 'commit-icons', className: 'CommitIcons' },
  DirTimeSimplifier: { id: 'dir-time-simplifier', className: 'DirTimeSimplifier' },

  // 油猴相关模块
  GreasyForkFeedbackMark: { id: 'greasy-fork-feedback-mark', className: 'GreasyForkFeedbackMark' },
  GreasyForkFeedbackGroup: { id: 'greasy-fork-feedback-group', className: 'GreasyForkFeedbackGroup' },
  GreasyForkScriptMark: { id: 'greasy-fork-script-mark', className: 'GreasyForkScriptMark' },
  GreasyForkSearchNavigator: { id: 'greasy-fork-search-navigator', className: 'GreasyForkSearchNavigator' },
  GreasyForkScriptInstalls: { id: 'greasy-fork-script-installs', className: 'GreasyForkScriptInstalls' },
  GreasyForkStatsPanel: { id: 'greasy-fork-stats-panel', className: 'GreasyForkStatsPanel' },
  GreasyForkTimeHelper: { id: 'greasy-fork-time-helper', className: 'GreasyForkTimeHelper' },

  // 控制加载顺序
  // GreasyForkScriptValuation 必须在 ScriptNavigator 之前，因为 ScriptNavigator 依赖 GreasyForkScriptValuation 的标签数据
  GreasyForkScriptValuation: { id: 'greasy-fork-script-valuation', className: 'GreasyForkScriptValuation' },
  GreasyForkScriptNavigator: { id: 'greasy-fork-script-navigator', className: 'GreasyForkScriptNavigator' },
}

/**
 * 模块类型定义
 */
export type AppModuleType = keyof typeof AppModule
export type ModuleId = typeof AppModule[AppModuleType]['id']
export type ModuleClassName = typeof AppModule[AppModuleType]['className']

// 模块构造函数映射（注册顺序按照先后顺序，优先级从高到低）,不包含AdEngine、TocEngine
export const MODULE_CONSTRUCTORS: Array<{ module: ModuleClassName, constructor: () => any }> = [
  {
    module: AppModule.StyleEnhancement.className, // 必须优先加载样式
    constructor: StyleEnhancement.getInstance,
  },
  {
    module: AppModule.ElementHider.className,
    constructor: ElementHider.getInstance,
  },
  {
    module: AppModule.NavbarMenu.className,
    constructor: NavbarMenu.getInstance,
  },
  {
    module: AppModule.QuickScroll.className,
    constructor: QuickScroll.getInstance,
  },
  {
    module: AppModule.FloorMarker.className,
    constructor: FloorMarker.getInstance,
  },
  {
    module: AppModule.AnswerNavigator.className,
    constructor: AnswerNavigator.getInstance,
  },
  {
    module: AppModule.CopyCopyright.className,
    constructor: CopyCopyright.getInstance,
  },
  {
    module: AppModule.CopyProtection.className,
    constructor: CopyProtection.getInstance,
  },
  {
    module: AppModule.LinkDirect.className,
    constructor: LinkDirect.getInstance,
  },
  {
    module: AppModule.BlockLogin.className,
    constructor: BlockLogin.getInstance,
  },
  {
    module: AppModule.PayWallHandler.className,
    constructor: PayWallHandler.getInstance,
  },
  {
    module: AppModule.StealthSearch.className,
    constructor: StealthSearch.getInstance,
  },
  {
    module: AppModule.NewTabLinks.className,
    constructor: NewTabLinks.getInstance,
  },
  {
    module: AppModule.MarkRead.className,
    constructor: MarkRead.getInstance,
  },
  {
    module: AppModule.SuperSearch.className,
    constructor: SuperSearch.getInstance,
  },
  {
    module: AppModule.SvgCopy.className,
    constructor: SvgCopy.getInstance,
  },
  {
    module: AppModule.KeyboardPagination.className,
    constructor: KeyboardPagination.getInstance,
  },
  {
    module: AppModule.HideSearchHistory.className,
    constructor: HideSearchHistory.getInstance,
  },
  {
    module: AppModule.HideSearchSuggestions.className,
    constructor: HideSearchSuggestions.getInstance,
  },
  {
    module: AppModule.HideSearchHotLists.className,
    constructor: HideSearchHotLists.getInstance,
  },
  {
    module: AppModule.CleanSearchHistory.className,
    constructor: CleanSearchHistory.getInstance,
  },
  {
    module: AppModule.ConversationFlow.className,
    constructor: ConversationFlow.getInstance,
  },
  {
    module: AppModule.DiscussionAnalytics.className,
    constructor: DiscussionAnalytics.getInstance,
  },
  {
    module: AppModule.QuickDownload.className,
    constructor: QuickDownload.getInstance,
  },
  {
    module: AppModule.ImageDetail.className,
    constructor: ImageDetail.getInstance,
  },
  {
    module: AppModule.ImagePreview.className,
    constructor: ImagePreview.getInstance,
  },
  {
    module: AppModule.UserAnalytics.className,
    constructor: UserAnalytics.getInstance,
  },
  {
    module: AppModule.FileIcons.className,
    constructor: FileIcons.getInstance,
  },
  {
    module: AppModule.CommitIcons.className,
    constructor: CommitIcons.getInstance,
  },
  {
    module: AppModule.DirTimeSimplifier.className,
    constructor: DirTimeSimplifier.getInstance,
  },

  // 主题
  {
    module: AppModule.ThemeInherit.className,
    constructor: ThemeInherit.getInstance,
  },
  {
    module: AppModule.ThemeSync.className,
    constructor: ThemeSync.getInstance,
  },
  {
    module: AppModule.ThemeStyle.className,
    constructor: ThemeStyle.getInstance,
  },

  {
    module: AppModule.BeautifyLink.className,
    constructor: BeautifyLink.getInstance,
  },
  {
    module: AppModule.TimeInterval.className,
    constructor: TimeInterval.getInstance,
  },
  {
    module: AppModule.AutoPagination.className,
    constructor: AutoPagination.getInstance,
  },

  // 油猴
  {
    module: AppModule.GreasyForkFeedbackMark.className,
    constructor: GreasyForkFeedbackMark.getInstance,
  },
  {
    module: AppModule.GreasyForkFeedbackGroup.className,
    constructor: GreasyForkFeedbackGroup.getInstance,
  },
  {
    module: AppModule.GreasyForkScriptMark.className,
    constructor: GreasyForkScriptMark.getInstance,
  },
  {
    module: AppModule.GreasyForkScriptValuation.className,
    constructor: GreasyForkScriptValuation.getInstance,
  },
  {
    module: AppModule.GreasyForkScriptNavigator.className,
    constructor: GreasyForkScriptNavigator.getInstance,
  },
  {
    module: AppModule.GreasyForkSearchNavigator.className,
    constructor: GreasyForkSearchNavigator.getInstance,
  },
  {
    module: AppModule.GreasyForkScriptInstalls.className,
    constructor: GreasyForkScriptInstalls.getInstance,
  },
  {
    module: AppModule.GreasyForkStatsPanel.className,
    constructor: GreasyForkStatsPanel.getInstance,
  },
  {
    module: AppModule.GreasyForkTimeHelper.className,
    constructor: GreasyForkTimeHelper.getInstance,
  },
]
